<template>
    <div>
        <x-header v-show="!isWeChar">
            <div slot="default" class="common__header--title">{{poster.name}}</div>
            <div @click="goBack" slot="overwrite-left" class="common__header--img"><img slot="icon" src="~assets/x3/ico/goback1.png" class="go-back"></div>
        </x-header>
        <div class="poster_page" id="poster_page">
            <!-- 原海报 -->
            <img v-show="false" id="my_poster" src="~assets/x3/channel/poster/registerChannel.jpg">
            <!-- 二维码默认尺寸为160*160 -->
            <qrcode v-show="false" id="my_qrcode" type="img" bg-color="#fff" :value="qrCodeShareLinkUrl"></qrcode>
            <!-- 画布 -->
            <canvas v-show="false" id="my_canvas"></canvas>
            <!-- 合成的海报 -->
            <img :src="newPosterUrl" width="100%">
        </div>

        <toast v-model="showToast" type="text" :position="position" :time="5000" width="16em">{{showToastText}}</toast>
    </div>
</template>

<script>
import SharePage from "src/js/sharePage"; //引入微信分享js
import Validation from "src/common/util/validation";
import { mapState } from 'vuex';
import { RequestUrl } from "src/common/url";
import { XInput, XButton, Loading, TransferDomDirective as TransferDom, XHeader, Qrcode, Toast } from 'vux';
import { Mutations, RouteUrl, WE_CHAT, Url_Key } from 'src/common/const';
export default {
    computed: mapState(['poster', "isInitData", "isWeChar", "isQueryPoster", "shareUuid", "saveInsure", "user", "isWeAuth"]),
    components: { XHeader, XInput, XButton, Qrcode, Toast },
    data() {
        return {
            multiple: 2.0,//缩小倍数为1309/414≈3.16,414=iPhonePlus宽;
            coverRight: 143,//二维码右侧与原始海报右侧距离
            coverBottom: 296,//二维码底部与原始海报底部距离
            newPosterUrl: "",//合成的图片src地址
            qrCodeShareLinkUrl: RequestUrl.BASE_URL,//分享的进入链接转地址
            id: "",
            imgLoadPoster: false, //原海报是否加载完毕
            imgLoadQrcode: false,//二维码是否加载完毕
            isShop: false,
            isInit: false,

            showToast: false,//是否显示提示内容
            showToastText: "长按图片保存后分享效果更佳",//提示内容
            position: "bottom",//提示位置
        }
    },
    watch: {
        imgLoadPoster(cur, old) {
            // console.log("海报加载完毕状态：" + cur + ",二维码加载完毕状态：" + this.imgLoadQrcode);
            if (cur && this.imgLoadQrcode) {
                // console.log("全部加载完毕===>最后是原海报加载完毕");
                this.initImg();//绘制海报
            }
        },
        imgLoadQrcode(cur, old) {
            // console.log("二维码加载完毕状态：" + cur + ",海报加载完毕状态：" + this.imgLoadPoster);
            if (cur && this.imgLoadPoster) {
                // console.log("全部加载完毕===>最后是二维码加载完毕");
                this.initImg();//绘制海报
            }
        },
    },
    beforeRouteEnter(to, from, next) {
        sessionStorage["SHOW_POSTER_FORM_URL"] = from.path;//刷新时的地址
        next();
    },
    // beforeMount() {
    //     this.initURIParameters();
    // },
    methods: {
        goBack() {
            this.$common.goBack(this);
        },
        // initURIParameters() {
        //     let url = window.location.href;;
        //     //解码URI--------------decodeURI不能完全解码,必须使用decodeURIComponent
        //     // let uuid = this.$common.getShareUrlKey(url, Url_Key.SHARE_UUID);
        //     let id = this.$common.getShareUrlKey(url, Url_Key.SHOW_POSTER);
        //     if (!this.isQueryPoster && typeof (id) != 'undefined' && id != undefined && id != null) {
        //         this.id = id;
        //         let data = {
        //             _this: this,
        //             id: id,
        //             type: "other"
        //         }

        //         this.$common.storeCommit(this, Mutations.SET_POSTER, data);
        //     } else if (!this.isQueryPoster) {
        //         //参数无法解析时跳转到首页
        //         this.$common.goUrl(this, RouteUrl.INDEX);
        //     }
        // },
        // initShare() {
        //     let _this = this;
        //     let parmList = [];
        //     let uuid = "";
        //     if (this.$common.isNotEmpty(this.saveInsure.refShareUUid) && (this.saveInsure.refereeData.storeFlag == "1" || this.saveInsure.refereeData.storeFlag == 1)) {
        //         sessionStorage["SHARE_COMMON_TYPE"] = "REF";
        //         uuid = this.saveInsure.refShareUUid;
        //     } else {
        //         if (this.user.isLogin) {
        //             uuid = this.$encode.hex_md5(this.user.userDto.userCode + ":1");
        //             this.$common.storeCommit(this, Mutations.SET_SHARE_UUID, uuid);
        //         }
        //         sessionStorage["SHARE_COMMON_TYPE"] = "USER";
        //         uuid = this.shareUuid;
        //     }

        //     let urlParm = {
        //         key: Url_Key.SHARE_UUID,
        //         value: uuid
        //     }
        //     let urlPro = {
        //         key: Url_Key.SHOW_POSTER,
        //         value: this.poster.id
        //     }
        //     parmList.push(urlPro);
        //     parmList.push(urlParm);
        //     //当前页面分享地址
        //     let shareUrl = RequestUrl.BASE_URL + RouteUrl.SHOW_POSTER + this.$common.setShareUrl(parmList);

        //     document.title = this.poster.name;

        //     let imgUrl = this.poster.imgUrl;
        //     if (imgUrl.indexOf("http://") < 0 && imgUrl.indexOf("https://") < 0) {
        //         //补全产品的图片路径
        //         imgUrl = RequestUrl.WEB_PATH + imgUrl;
        //     }

        //     // debugger
        //     //店铺海报
        //     if (this.poster.type == 1) {
        //         //二维码地址
        //         this.qrCodeShareLinkUrl = RequestUrl.BASE_URL + RouteUrl.SHOP_INDEX + this.$common.setShareUrl(parmList);
        //     } else {
        //         let urlProPro = {
        //             key: Url_Key.PRODUCT_ID,
        //             value: this.poster.productId
        //         }
        //         parmList.push(urlProPro);
        //         //二维码地址
        //         this.qrCodeShareLinkUrl = RequestUrl.BASE_URL + RouteUrl.DETAILS + this.$common.setShareUrl(parmList);
        //     }
        //     // debugger
        //     _this.$common.saveShare("海报", _this, 6);
        //     let weChatData = {
        //         _this: this,
        //         shareData: {
        //             title: this.poster.name,
        //             desc: this.poster.summaryInfo,
        //             imgUrl: imgUrl,
        //             url: shareUrl,
        //             _this: this,
        //             type: 6
        //         }
        //     };
        //     SharePage.weChatShare(weChatData);
        // },
        initImg() {
            // this.initShare();
            document.title = this.poster.name;
            //输出二维码和文字到海报
            this.outputDataToPoster();
        },
        //刷新海报内容
        refreshPoster() {
            //提示长安保存文本
            this.showToast = true;
            //输出二维码和文字到海报
            this.outputDataToPoster();
        },
        //输出二维码和文字到海报
        outputDataToPoster() {
            let _this = this;
            //延时等分享参数和二维码地址解析好后再画二维码
            setTimeout(() => {
                _this.$common.storeCommit(_this, Mutations.UPDATE_LOADING_STATUS, true);//loading
                // //海报图片不为空
                // if (!_this.$common.isEmpty(_this.poster.bigImgUrl)) {
                //获取海报img标签
                let my_poster = document.getElementById("my_poster");
                //获取二维码标签
                let my_qrcode = document.getElementById("my_qrcode");
                //获取二维码img标签
                let my_qrcode_img = my_qrcode.getElementsByTagName("img")[0];
                //获取画布标签
                let canvas = document.getElementById("my_canvas");
                //------------处理海报
                //图片原始尺寸
                let coverW_p = my_poster.naturalWidth;
                let coverH_p = my_poster.naturalHeight;
                // console.log("海报原始尺寸 ====" + coverW_p + "×" + coverH_p);

                //计算画到画布上的尺寸
                //缩小宽高
                let useW_p = Math.ceil(parseInt(coverW_p / _this.multiple));
                let useH_p = Math.ceil(parseInt(coverH_p / _this.multiple));
                // console.log("海报缩小尺寸 ====" + useW_p + "×" + useH_p);
                canvas.setAttribute("width", useW_p);//画布原始尺寸请保持和画图时使用的尺寸保持一致
                canvas.setAttribute("height", useH_p);//画布原始尺寸请保持和画图时使用的尺寸保持一致

                //获取画布工具
                let ctx = canvas.getContext("2d");
                //将x=0,y=0位置的海报cover尺寸以use尺寸画到画布的x=0,y=0的位置上
                ctx.drawImage(my_poster, 0, 0, coverW_p, coverH_p, 0, 0, useW_p, useH_p);

                // //要绘制的字符串
                // if (_this.$common.isNotEmpty(_this.poster.animatedTexts)) {
                //     for (let i = 0; i < _this.poster.animatedTexts.length; i++) {
                //         let obj = _this.poster.animatedTexts[i];
                //         ctx.fillStyle = obj.color;
                //         ctx.font = obj.fontSize + "px " + obj.fontType;
                //         _this.canvasTextAutoLine(obj.text, ctx, obj.coordinateX, obj.coordinateY, obj.width, obj.height, obj.rowSpacig);
                //     }
                // }
                //------------处理二维码
                //图片原始尺寸
                let coverW_q = my_qrcode_img.naturalWidth;
                let coverH_q = my_qrcode_img.naturalHeight;
                // console.log("二维码原尺寸 ====" + coverW_q + "×" + coverH_q);
                // alert("二维码原尺寸 ====" + coverW_q + "×" + coverH_q);

                let beishu = 2.0;

                //缩小宽高
                let useW_q = Math.ceil(parseInt(coverW_q / _this.multiple / beishu));
                let useH_q = Math.ceil(parseInt(coverH_q / _this.multiple / beishu));

                // let beishu = 1.0;
                // if (coverW_q > 320) {
                //     beishu = coverW_q / 320;//四舍五入取整
                //     //太大的beishu倍
                //     useW_q = Math.ceil(parseInt(useW_q / beishu));
                //     useH_q = Math.ceil(parseInt(useH_q / beishu));
                // }
                // if (coverW_q < 320) {
                //     beishu = 320 / coverW_q;//四舍五入取整
                //     //太小的beishu倍
                //     useW_q = Math.ceil(parseInt(useW_q * beishu));
                //     useH_q = Math.ceil(parseInt(useH_q * beishu));
                // }

                // alert("二维码缩小尺寸 ====" + useW_q + "×" + useH_q);
                // console.log("二维码缩小尺寸 ====" + useW_q + "×" + useH_q);
                //计算二维码距离右下角边距
                let right = coverW_p - _this.coverRight - coverW_q;
                let bottom = coverH_p - _this.coverBottom - coverH_q;

                //系统配置的尺寸
                if (_this.$common.isNotEmpty(_this.poster.coordinateXQRCode)) {
                    right = parseInt(_this.poster.coordinateXQRCode);//二维码X轴位置
                }
                if (_this.$common.isNotEmpty(_this.poster.coordinateYQRCode)) {
                    bottom = parseInt(_this.poster.coordinateYQRCode);//二维码Y轴位置
                }

                // alert("二维码画的原始位置 ====R=" + right + "---B=" + bottom);
                // console.log("二维码画的原始位置 ====R=" + right + "---B=" + bottom);
                let useRight = Math.ceil(parseInt(right / _this.multiple));
                let useBottom = Math.ceil(parseInt(bottom / _this.multiple));
                if (coverW_q > 686) {
                    useRight -= (coverW_q - useW_q * _this.multiple) / _this.multiple;//向左移动此px单位
                    useBottom -= (coverH_q - useH_q * _this.multiple) / _this.multiple;//向上移动此px单位
                }
                if (coverW_q < 686) {
                    useRight += (coverW_q - useW_q * _this.multiple) / _this.multiple;//向右移动此px单位
                    useBottom += (coverH_q - useH_q * _this.multiple) / _this.multiple;//向下移动此px单位
                }

                //系统配置的尺寸
                if (_this.$common.isNotEmpty(_this.poster.widthQRCode)) {
                    useW_q = parseInt(_this.poster.widthQRCode);//二维码宽
                }
                if (_this.$common.isNotEmpty(_this.poster.heightQRCode)) {
                    useH_q = parseInt(_this.poster.heightQRCode);//二维码高
                }

                // console.log("二维码画的位置 ====R=" + useRight + "---B=" + useBottom);
                // alert("二维码画的位置 ====R=" + useRight + "---B=" + useBottom);


                //将x=0,y=0位置的二维码cover尺寸以use尺寸画到画布的x=useRight,y=useBottom的位置上
                useRight += 25;
                useBottom += 100;

                let border = 10;//边框大小
                ctx.lineJoin = "round";//圆角，默认。创建尖角。
                ctx.lineWidth = border;
                ctx.shadowOffsetX = 3;//X轴向右偏移
                ctx.shadowOffsetY = 3;//Y轴向下偏移
                ctx.shadowBlur = 10;//半径
                ctx.strokeStyle = "white";//笔触颜色
                ctx.shadowColor = "rgba(0,0,0,0.7)";//RGB颜色和透明度
                // 绘制 参数后两位 像素的圆角矩形框
                ctx.strokeRect(useRight - border + 5, useBottom - border + 5, useW_q + border, useH_q + border);
                // 绘制 参数后两位 像素的矩形
                // ctx.fillStyle = "white";//渲染颜色
                // ctx.fillRect(useRight, useBottom, useW_q + border, useH_q + border);

                ctx.shadowOffsetX = 0;//X轴向右偏移
                ctx.shadowOffsetY = 0;//Y轴向下偏移
                ctx.shadowBlur = 0;//半径
                ctx.shadowColor = "rgba(0,0,0,1)";//RGB颜色和透明度
                ctx.drawImage(my_qrcode_img, 0, 0, coverW_q, coverH_q, useRight, useBottom, useW_q, useH_q);

                // ctx.fillStyle = "#000";//颜色
                // ctx.font = "17px 微软雅黑";//字体大小和样式
                // ctx.textBaseline = "top";//设置或返回在绘制文本时的当前文本基线

                // let r = useRight + 9;
                // let b = useBottom + useH_q + 10;
                // ctx.fillText("长按识别二维码，测试是否超过页面边距，谢谢。", r, b);

                _this.newPosterUrl = _this.convertCanvasToImage(canvas).src;
                _this.$common.storeCommit(_this, Mutations.UPDATE_LOADING_STATUS, false);//loading

                if (_this.$common.isEmpty(_this.poster.animatedTexts)) {
                    //提示长安保存文本
                    this.showToast = true;
                } else {
                    //动态海报输出完毕，显示文字修改按钮，
                    _this.printPosterDone = true;
                }
                console.log("新文件大小====" + _this.getFileSize(_this.newPosterUrl) + "kb");

                //移除原有的HTML元素
                // var parent = document.getElementById("poster_page");
                // parent.removeChild(my_poster);
                // parent.removeChild(my_qrcode);
                // parent.removeChild(canvas);
                // }
            }, 100);
        },
        // 从canvas提取图片image
        convertCanvasToImage(canvas) {
            //新Image对象，可以理解为DOM  
            let image = new Image();
            // canvas.toDataURL 返回的是一串Base64编码的URL，当然,浏览器自己肯定支持  
            // 指定格式和质量,默认为png,原始质量=1.0
            image.src = canvas.toDataURL("image/png");
            return image;
        },
        /**
         * str:要绘制的字符串
         * ctx = canvas.getContext("2d");
         * initX:绘制字符串起始x坐标
         * initY:绘制字符串起始y坐标
         * textWidth:文字区域宽度
         * textHeigth:文字区域高度
         * lineHeight:字行高，自己定义个值即可
         */
        canvasTextAutoLine(str, ctx, initX, initY, textWidth, textHeigth, lineHeight) {
            // console.log(str);
            var lineWidth = 0;//每行文字总宽度
            var lastSubStrIndex = 0;//每行第一个字符下标
            var lineHeightRow = initY;//行间距起始位置
            for (let i = 0; i < str.length; i++) {
                if (lineHeightRow < initY + textHeigth) { //在指定高度内才绘制文本
                    lineWidth += ctx.measureText(str[i]).width;//加该文字的宽度
                    if (lineWidth > textWidth) {//超过指定宽度时（防止边界出现的问题）
                        ctx.fillText(str.substring(lastSubStrIndex, i), initX, lineHeightRow);//绘制本行文本内容
                        lineHeightRow += lineHeight;//加一行的位置
                        lineWidth = 0;//恢复默认每行文字总宽度
                        lastSubStrIndex = i;//正常超出时换行
                    }
                    if (i == str.length - 1) {
                        ctx.fillText(str.substring(lastSubStrIndex, i + 1), initX, lineHeightRow);
                    }
                }
            }
        },
        //获取文件大小
        getFileSize(base64Code) {
            let str = base64Code.substring(22);
            let equalIndex = str.indexOf('=');
            if (str.indexOf('=') > 0) {
                str = str.substring(0, equalIndex);
            }
            let strLength = str.length;//原始大小
            let fileLength = Math.ceil(parseInt(strLength - (strLength / 8) * 2) / 1024);;
            return fileLength;
        },
        // //获取图片base-64编码,img = new Image()
        // getBase64Image(imageObj) {
        //     let canvas = documdocument.createElement("canvas");
        //     canvas.width = imageObj.width;
        //     canvas.height = imageObj.height;
        //     let ctx = canvas.getContext("2d");
        //     ctx.drawImage(imageObj, 0, 0, imageObj.width, imageObj.height);
        //     let ext = imageObj.src.substring(imageObj.src.lastIndexOf(".") + 1).toLowerCase();
        //     let dataURL = canvas.toDataURL("image/" + ext);//转换为data
        //     return dataURL;
        // },
        //初始化当前页面信息
        baseInit() {
            let _this = this;
            this.isInit = true;
            _this.$common.storeCommit(_this, Mutations.UPDATE_LOADING_STATUS, true);
            document.getElementById('my_poster').onload = function () {
                // console.log("海报--加载完成");
                _this.imgLoadPoster = true;
            };
            document.getElementById("my_qrcode").getElementsByTagName("img")[0].onload = function () {
                // console.log("二维码--加载完成");
                _this.imgLoadQrcode = true;
            };
        },

        //初始化分享信息
        initShareData(shareUrl, headUrl) {
            //微信分享初始数据
            let shareLinkData = {
                _this: this,
                shareData: {
                    title: "恒华出行宝",
                    desc: this.user.userDto.nickName + WE_CHAT.shareDesc_channel,
                    imgUrl: headUrl,
                    url: shareUrl,
                    _this: this,
                    type: 8//渠道
                }
            };
            // 初始微信分享
            SharePage.weChatShare(shareLinkData);
            // console.log(shareLinkData);
        },
    },

    mounted() {
        let _this = this;
        this.$init.subPageInit(this);

        //头像地址
        let headUrl = this.user.userDto.headUrl;
        if (this.$common.isEmpty(headUrl)) {
            //补全头像的图片路径
            headUrl = RequestUrl.WEB_PATH + "sticcxb/upload/userHeadImg/default/headImgDefault.jpg";
        } else {
            if (headUrl.indexOf("http:") < 0 && headUrl.indexOf("https:") < 0) {
                //补全头像的图片路径
                headUrl = RequestUrl.WEB_PATH + "sticcxb/" + headUrl;
            }
        }

        if (this.user.isLogin) {
            let shareId = this.$encode.hex_md5(this.user.userDto.userCode + ":1");//渠道分享

            //初始化分享信息
            this.$common.saveShare("渠道二维码", this, 8);//8=渠道

            let parmList = [];
            let urlParm = {
                key: Url_Key.SHARE_UUID,
                value: shareId
            }
            parmList.push(urlParm);
            //海报二维码分享地址,例如：
            //http://msi:8080/sticcxb/#/sticcxb/registeraccept?shareId=e56ef558dfbd874516b8f071a1b62278e49e(WX00000025加混淆码再加密后的)
            this.qrCodeShareLinkUrl = RequestUrl.BASE_URL + RouteUrl.REGISTER_ACCEPT + this.$common.setShareUrl(parmList);

            //初始化当前页面信息
            this.baseInit();

            //初始化分享信息
            this.initShareData(this.qrCodeShareLinkUrl, headUrl);
        } else {
            this.$common.goBack(this);
        }
    }
}
</script>

<style lang="scss" scoped>
// .poster_page {
//   background: white;
//   padding: 10px;
//   border-top: 1px solid #e7e7e7;
// }
//input区域
.inputDiv {
  margin: 15px auto;
  width: 95%;
  height: auto;
  border-radius: 5px;
  background-color: white;
  span {
    font-size: 14px;
  }
  .weui-cell {
    border-top: 1px solid #efefef;
  }
  .weui-cell:before {
    border-top: 0px;
  }
}
</style>
